import json
import csv
import re
from collections import Counter
from pathlib import Path
import logging

def process_file(filepath, keyword):
    path = Path(filepath)
    if not path.exists():
        logging.error(f"文件不存在: {filepath}")
        print(f"[错误] 文件不存在：{filepath}")
        return

    logging.info(f"开始处理文件: {filepath}")

    if filepath.endswith(".json"):
        with open(filepath, "r", encoding="utf-8") as f:
            data = json.load(f)
            content = json.dumps(data)  # 统一转成字符串处理
    elif filepath.endswith(".csv"):
        with open(filepath, "r", encoding="utf-8") as f:
            reader = csv.reader(f)
            content = "\n".join([",".join(row) for row in reader])
    else:
        logging.error("不支持的文件格式")
        print("[错误] 只支持 .json 或 .csv 文件")
        return

    matches = re.findall(fr"\b{re.escape(keyword)}\b", content, flags=re.IGNORECASE)
    count = Counter(matches)

    print(f"🔍 在文件中找到 {len(matches)} 次关键词「{keyword}」")
    logging.info(f"关键词统计完成：{count}")